package com.story.util;

import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Pyx
 * @PACKAGE_NAME : com.story.util
 * @FileName: SendSmsUtil
 * @date 2020/5/19 10:09
 */
public class SendSmsUtil {


    private static final String APPID = "19862";
    private static final String PROJECT = "OIgrd3";
    private static final String SIGNATURE = "c698ed7f446c8e4d36265a87b2231ae7";
    private static final String URL = "https://api.mysubmail.com/message/xsend";

    /**
     * 构造请求Body体
     */
    private static String buildRequestBody(String to, String code) {
        if (null == to || null == code || to.isEmpty()) {
            System.out.println("buildRequestBody():  is null.");
            return null;
        }

        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();

        keyValues.add(new BasicNameValuePair("appid", APPID));
        keyValues.add(new BasicNameValuePair("project", PROJECT));
        keyValues.add(new BasicNameValuePair("signature", SIGNATURE));
        keyValues.add(new BasicNameValuePair("to", to));
        String vars = "{\"code\":\"" + code + "\"}";
        keyValues.add(new BasicNameValuePair("vars", vars));
        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
    }

    public static String sendPhoneSms(String phoneNum) throws Exception {
        String random = getRandom();
        String body = buildRequestBody(phoneNum, random);

        if (null == body || body.isEmpty()) {
            System.out.println("body is null.");
            return null;
        }

        //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
        CloseableHttpClient client = HttpClients.custom()
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                        (x509CertChain, authType) -> true).build())
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();

        HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
                .setUri(URL)
                .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                .setEntity(new StringEntity(body)).build());

        System.out.println(response.toString()); //打印响应头域信息
        System.out.println(EntityUtils.toString(response.getEntity())); //打印响应消息实体
        return random;
    }

    public static String
    getRandom() {
        return (int) ((Math.random() * 9 + 1) * 100000) + "";
    }

}
